package com.weaver.seconddev.tl.reghook;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.weaver.common.hrm.util.Util;
import com.weaver.common.i18n.tool.util.I18nContextUtil;
import com.weaver.eteams.file.client.file.FileObj;
import com.weaver.loom.context.annotation.WeaHookReg;
import com.weaver.loom.context.domain.AppInfo;
import com.weaver.loom.context.domain.WeaHookRequest;
import com.weaver.loom.context.domain.WeaHookResponse;
import com.weaver.loom.context.register.RegHookEvent;
import com.weaver.verupgrade.conn.RecordSet;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;

import java.util.Map;

@Slf4j
@WeaHookReg(code = "FILE_APP_STORAGE_HOOK_009", order = 0)
public class FileobjHook extends  RegHookEvent {

    @Override
    public WeaHookResponse handle(WeaHookRequest request, WeaHookResponse response, AppInfo appInfo) throws Exception {
        //入参，修改入参并不会影响到埋点的原始数据
        Map<String, Object> params = request.getParams();
        log.error("params12345:"+params.toString());
        //前面同一埋点多个二开，前面链路节点二开代码执行的结果
        Object result = response.getResult();
        //log.error("result:"+ (result!=null));
        Map<String,Object> upload4ModuleParam = (Map<String, Object>) params.get("upload4ModuleParam");
        //log.error("upload4ModuleParam11:"+upload4ModuleParam.toString());
        FileObj fileObj = (FileObj) params.get("FileObj");

        //todo 处理params 与 传进来的前面链路的 result
        //如 未读取response 中的result数据 直接将新的数据写入response 会覆盖前面链路的返回值

        //log.error("fileObj:"+fileObj.toString());
        Long doc_id = fileObj.getDocId();
        Long upload_employee_id = fileObj.getUploadEmployeeId();
        Long fileId = fileObj.getId();
        if(upload4ModuleParam != null ){
            String customParam = (String) upload4ModuleParam.get("customParam");
            //log.error("customParam:"+customParam.toString());
            if(StringUtils.isNotBlank(customParam)){
                JSONObject jsonObject = JSON.parseObject(customParam);
                Long requestId = Long.valueOf(jsonObject.getString("requestId"));
                log.error("fileId:"+fileId+"----requestId:"+requestId);
                shareTmpDoc(fileId,requestId,doc_id,upload_employee_id);
            }
        }

        if (result != null) {} else {
            //如果没有实际的返回数据可以不设置result，不要自己插入不支持序列化的类型，不然会报错
            response.setResult(result);
        }
        return response;//返回结果
    }

    @Override
    public void rollBack(WeaHookRequest request, WeaHookResponse response, AppInfo appInfo) throws Exception {

    }

    public void shareTmpDoc( Long fileid, Long requestId,Long doc_id,Long upload_employee_id){
        RecordSet rs = I18nContextUtil.getBean(RecordSet.class);
        rs.executeForWf("SELECT workflow_requestbase.workflowid AS workflowid " +
                "FROM e10_core_business.wfc_requestbase workflow_requestbase " +
                "WHERE workflow_requestbase.requestid = ? " +
                "AND workflow_requestbase.delete_type = 0 " +
                "AND workflow_requestbase.tenant_key = 'tl2k2r96ty'",requestId);
        Long workflowid =0L;
        if(rs.next()){
            workflowid = Util.getLongValue(rs.getString("workflowid"));
        }
        log.error("workflowid33333333:"+workflowid);
        //只处理内部人员，只处理流程上传附件
        if( workflowid > 0) {
            //判断建模表是否有配置
            boolean isAll = true;
            boolean isCfg = false;
            String tmpSql = "SELECT uf_editperset.lcid AS lcid " +
                    "FROM e10_common.uf_editperset " +
                    "WHERE uf_editperset.delete_type = 0 " +
                    " AND uf_editperset.tenant_key = 'tl2k2r96ty' ";
            rs.executeQuery(tmpSql);
            while (rs.next()){
                isAll = false;
                String tempLcid = rs.getString("lcid");
                if((","+tempLcid+",").contains(","+workflowid+",")){
                    isCfg = true;
                }
            }
            if(isAll || isCfg) {
                /**
                 * 1、附件上传字段 创建人在上传文档附件之后，可以编辑文档，在流程提交之后收回文档的编辑权限 ，后续节点 文档权限按照表单字段属性赋予，流程在退回到发起节点赋予创建人编辑权限，归档后所有流程参与人都只有只读权限（通过建模配置流程，建模表为空则都生效，配置流程则配置的流程生效）。
                 * 目前已开发实现
                 *
                 * 现需要合同范本也实现同样的效果
                 * 流程发起节点，合同范本生成的合同附件传至附件字段后，流程创建人可以编辑文档，在流程提交之后收回文档的编辑权限 ，后续节点 文档权限按照表单字段属性赋予，流程在退回到发起节点赋予创建人编辑权限，归档后所有流程参与人都只有只读权限（通过建模配置流程，建模表为空则都生效，配置流程则配置的流程生效）。
                 */
           /*     ShareinnerInfo shareinnerInfo = new ShareinnerInfo();
                int opertor = operator.getUID();
                int slevel = 2;
                int downloadlevel = 1;

                char flag = Util.getSeparator();
                String ProcPara = docId + "" + flag + "1" + flag + "10" + flag + "0" + flag + "2" + flag + opertor + flag + "0" + flag + "0" + flag + "0" + flag + "0" + flag + "0" + flag + "1" + flag + "1";
                rs.writeLog("\n2770213 => ProcPara-合同范本 = " + ProcPara);
                rs.executeProc("DocShare_FromDocSecCatI_DL", ProcPara);
                人员，安全级别10
                shareinnerInfo.AddShareContainDownloadLevel(docId, 1, opertor, 10, slevel, 1, opertor, "ShareinnerDoc", 1, downloadlevel);
*/

                DocShareUtil.addUserShare(rs,doc_id,upload_employee_id);
            }
        }
    }



}
